import cgi
import wsgiref.handlers
import os
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from cgi import parse_qs, escape
from mymodel import *
 
class MainPage(webapp.RequestHandler):
  def get(self):
    Data=""
    if users.get_current_user():
      mydata = LifeBit.all()
      mydata.filter('User =',users.get_current_user())
      mydata.order('-Date')
      Data=mydata.fetch(10)
    if users.get_current_user():
      url = users.create_logout_url(self.request.uri)
      url_linktext = 'Logout'
    else:
      url = users.create_login_url(self.request.uri)
      url_linktext = 'Login'

    template_values = {
      'Data': Data,
      'user': users.get_current_user(),
      'LOGURL': url,
      'url_linktext':url_linktext,
      }

    path = os.path.join(os.path.dirname(__file__), 'MainPage.htm')
    self.response.out.write(template.render(path, template_values))
    
class ViewRender(webapp.RequestHandler):
  def get(self):
    Data=""
    if users.get_current_user():
      mydata = LifeBit.all()
      mydata.filter('User =',users.get_current_user())
      mydata.order('-Date')
      Data=mydata.fetch(10)
    if users.get_current_user():
      url = users.create_logout_url(self.request.uri)
      url_linktext = 'Logout'
    else:
      url = users.create_login_url(self.request.uri)
      url_linktext = 'Login'

    template_values = {
      'Data': Data,
      'user': users.get_current_user(),
      'LOGURL': url,
      'url_linktext':url_linktext,
      }

    path = os.path.join(os.path.dirname(__file__), 'SimpleView.htm')
    self.response.out.write(template.render(path, template_values))

class ExpenseView(webapp.RequestHandler):
  def get(self):
    Data=""
    if users.get_current_user():
      mydata = LifeBit.all()
      mydata.filter('User =',users.get_current_user())
      mydata.filter('Application =','APP_EXPENSECALC');
      mydata.order('-Date')
      Data=mydata.fetch(10)
    template_values = {
      'Data': Data,
      'user': users.get_current_user(),
      }

    path = os.path.join(os.path.dirname(__file__), 'expenseview.htm')
    self.response.out.write(template.render(path, template_values))

class FetchExpense(webapp.RequestHandler):
    def post(self):
      iLabel=cgi.escape(self.request.get('Label'))
      Int=int(cgi.escape(self.request.get('Amount')))
      expense=bool(cgi.escape(self.request.get('Expense')))
      if(not expense):
        Int=-1*Int;
      datum=LifeBit(Application='APP_EXPENSECALC',Label=iLabel,INT=Int, User=users.get_current_user(),)
      datum.put()
      self.redirect('expenseview')
    def get(self):
      template_values = template_values = {
         'Users': users,
        }
      path = os.path.join(os.path.dirname(__file__), 'fetchexpense.htm')
      self.response.out.write(template.render(path, template_values))

class fetch_data(webapp.RequestHandler):
  def post(self):
    iLocation=cgi.escape(self.request.get('Location'))
    iContent=cgi.escape(self.request.get('Content'))
    iURL=cgi.escape(self.request.get('URL'))
    iLabel=cgi.escape(self.request.get('Label'))
    datum=LifeBit(Location=iLocation,Content=iContent,Label=iLabel,URL=iURL,User=users.get_current_user())
    datum.put()
    self.redirect('/view')

class FetchPage(webapp.RequestHandler):
  def get(self):
    template_values = template_values = {
         'Users': users,
      }
    path = os.path.join(os.path.dirname(__file__), 'fetchpage.htm')
    self.response.out.write(template.render(path, template_values))

class ShowData(webapp.RequestHandler):
  def get(self):
    parameters = parse_qs(os.environ.get('QUERY_STRING', ''))
    if 'key' in parameters:
        key = escape(parameters['key'][0])
    else:
        self.response.out.write("<b>NONE</b>")
        return
    Data =db.get(key)
    #Do not allow other users to view this data
    if(Data.User!=users.get_current_user()):
      self.response.out.write("<b>NONE</b>")
      return
    if users.get_current_user():
      url = users.create_logout_url(self.request.uri)
      url_linktext = 'Logout'
    else:
      url = users.create_login_url(self.request.uri)
      url_linktext = 'Login'
    template_values = {
      'datum': Data,
      'user': users.get_current_user(),
      'LOGURL': url,
      'url_linktext':url_linktext,
      }
    path = os.path.join(os.path.dirname(__file__), 'View.htm')
    self.response.out.write(template.render(path, template_values))

def main():
  application = webapp.WSGIApplication(
                                       [('/', MainPage),
                                        ('/fetch_data', fetch_data),
                                        ('/fetchpage', FetchPage),
                                        ('/getjson', GetDataJSON),
                                        ('/view', ViewRender),
                                        ('/fetchexpense',FetchExpense),
                                        ('/expenseview',ExpenseView),
                                        ('/showdata', ShowData)
                                        ],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()
